﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web.UI;
using System.Xml;
using BUS;
using DTO;

namespace WebRaoVat
{
    public partial class DangBai : System.Web.UI.Page
    {
        public NguoiDungDTO nguoiDungHienTai;
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["TrangHienTai"] = "DangBai.aspx";

            if (Session["NguoiDungDangDangNhap"] == null || Session["NguoiDungDangDangNhap"].ToString().Length <= 0)
            {
                //Response.Redirect("Default.aspx");
            }

            nguoiDungHienTai = NguoiDungBUS.layNguoiDungTheoTen(Session["NguoiDungDangDangNhap"].ToString());

            Session["MaNgonNgu"] = Config._MANGONNGU.ToString();

            if (!IsPostBack)
            {
            }
        }
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Page.Theme = ((XmlElement)XL_XML.ReadNodeSingle(XL_XML.ReadDocumentFile(Server.MapPath("Gui.xml")),
            "/GIAODIEN/THEME")).GetAttribute("ten");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (nguoiDungHienTai == null)
                return;
            string noiDung = CKEditorControl1.Text;
            if ("" == noiDung)
                return;

            string tenTinRaoVat = txtTenTin.Text;
            int gia = 0;
            try
            {
                gia = int.Parse(txtGia.Text);
            }
            catch (Exception)
            {
            }

            string thumbnail = "";
            if ("" != FileUploadHinhDaiDien.PostedFile.FileName)
            {
                string duongDan = Server.MapPath("~/Pictures");
                string tenthat = Guid.NewGuid().ToString() + "." + FileUploadHinhDaiDien.PostedFile.FileName.Split('.')[1];
                duongDan += "/" + tenthat;
                FileUploadHinhDaiDien.PostedFile.SaveAs(duongDan);

                int _count = duongDan.LastIndexOf("\\");
                thumbnail = duongDan.Remove(0, _count + 1);
            }

            int ngonNgu = Config._MANGONNGU;
            int diaDiem = DiaDiemBUS.getMa(DropDownDiaDiem.Text);
            int maDanhMuc = DanhMucConBUS.getMa(DropDownListChuyenMuc.Text);
            //int thoiHanLuuTin = int.Parse(DropDownListThoiHanLuuTin.Text);

            try
            {
                TinRaoVatDTO tinRaoVat = new TinRaoVatDTO();
                tinRaoVat.TenTinRaoVat = tenTinRaoVat;
                if (thumbnail != "")
                    tinRaoVat.Thumbnail = thumbnail;
                tinRaoVat.GiaTien = gia;
                tinRaoVat.NoiDungTinRaoVat = noiDung;
                tinRaoVat.ThoiGianDang = DateTime.Now;
                tinRaoVat.SoLanXem = 0;
                tinRaoVat.MaDiaDiem = diaDiem;
                tinRaoVat.MaNgonNgu = ngonNgu;
                tinRaoVat.MaNguoiDung = nguoiDungHienTai.MaNguoiDung;
                tinRaoVat.MaDanhMucCon = maDanhMuc;
                tinRaoVat.Deleted = 0;
                tinRaoVat.ThoiGianUp = DateTime.Now;

                TinRaoVatBUS.Insert(tinRaoVat);            

                //Phần gửi mail            
                StreamReader sr = new StreamReader(Server.MapPath("TemplateMail/TemplateGoiTinRaoVat.htm"));

                sr = File.OpenText(Server.MapPath("TemplateMail/TemplateGoiTinRaoVat.htm"));              

                string content = sr.ReadToEnd();
                content = content.Replace("[Sender]", "B1_Group");
                content = content.Replace("[ChuyenMuc]", "<b>" + DanhMucConBUS.getTenDanhMuc(tinRaoVat.MaDanhMucCon) + "</b>");
                content = content.Replace("[TenTinRaoVat]", tinRaoVat.TenTinRaoVat);
                content = content.Replace("[LienKet]", "http://localhost:5798/ChiTietTinRao.aspx?MaTin=" +
                    TinRaoVatBUS.LayTinRaoVatTheoTen_NoiDung_ThoiGianDang(tinRaoVat.TenTinRaoVat, tinRaoVat.NoiDungTinRaoVat, tinRaoVat.ThoiGianDang).MaTinRaoVat.ToString());
                content = content.Replace("[DateTime]", DateTime.Now.ToString());

                List<EmailDangKyNhanTinRaoVatDTO> DSMailDK = EmailDangKyNhanTinRaoVatBUS.LayDSTheoMaDanhMucCon(tinRaoVat.MaDanhMucCon);                

                for (int iChiSo = 0; iChiSo < DSMailDK.Count; ++iChiSo)
                {
                    if (SendMail("Rao vặt - B1 Group (" + tinRaoVat.TenTinRaoVat + ")", content, DSMailDK[iChiSo].EmailNhanTinRaoVat, true, false) == false)
                    {
                        return;
                    }
                }                
            }
            catch (System.Exception ex)
            {

            }
        }

        public static string FormAddress
        {
            get
            {
                SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                return cfg.Network.UserName;
            }
        }

        private bool SendMail(string subject, string body, string to, bool isHtml, bool isSSL)
        {
            try
            {
                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress(FormAddress, "Rao vặt - B1 Group");
                    mail.To.Add(to);
                    mail.Subject = subject;
                    mail.Body = body;
                    mail.IsBodyHtml = isHtml;
                    SmtpClient client = new SmtpClient();
                    client.EnableSsl = isSSL;
                    client.Send(mail);
                }
            }
            catch (System.Exception ex)
            {
                return false;
            }

            return true;
        }

        private void ShowMessage(string mess)
        {
            string strBuilder = "<script language='javascript'>alert('" + mess + "')</script>";
            Response.Write(strBuilder);
        }
    }
}
